<template>
  <el-pagination
    class="paging"
    :style="style"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page.sync="currentPage"
    :page-size="size"
    :total="total"
    :page-sizes="pagesSizes"
    :pager-count="5"
    :layout="layout"
    :background="background"
  ></el-pagination>
</template>

<script>
  export default {
    props: {
      func: {
        type: Function,
      },
      layout: {
        type: String,
        default: 'total,sizes, prev, pager, next,jumper, ->',
      },
      sizeNum: {
        type: Number,
        default: 15,
      },
      pagesSizes: {
        type: Array,
        default: () => {
          return [5, 10, 15, 20, 30, 50];
        },
      },
      position: {
        type: String,
        default: 'left',
      },
      background: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        size: this.sizeNum,
        currentPage: 1,
        tempPage: 1,
        total: 0,
      };
    },
    watch: {
      sizeNum(value) {
        this.size = value;
      },
    },
    computed: {
      style() {
        return { textAlign: this.position };
      },
    },
    mounted() {
    },
    methods: {
      refresh() {
        this.search(this.tempPage);
      },
      handleSizeChange(size) {
        this.size = size;
        this.tempPage = 1;
        this.refresh();
      },
      handleCurrentChange(current) {
        this.tempPage = current;
        this.refresh();
      },
      search(currentPage) {
        if (this.func) {
          this.tempPage = currentPage;
          this.func(currentPage, this.size, this.setResultCallback);
        }
      },
      setResultCallback(records, recordCount) {
        if (records.length == 0 && this.tempPage > 1 && this.currentPage > 1) this.search(--this.currentPage);
        else {
          this.total = recordCount;
          this.currentPage = this.tempPage; //这里可能会出现bug，当前页应该根据total来设置，这里存在本地是为了实现返回时能到之前的页面，实际上可能已经没有这么多页数了
        }
      },
    },
  };
</script>

<style scoped lang="less">
  .paging {
    padding: 5px 0;
    border-radius: 4px;
    min-height: 28px;
  }
</style>
